package com.zbbt.sportslottery.ui.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import org.apache.http.Header;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gc.materialdesign.views.ProgressBarCircularIndetermininate;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.ui.widget.imageshow.ImagePagerAdapter;
import com.zbbt.sportslottery.ui.widget.imageshow.ImageShowViewPager;
import com.zbbt.sportslottery.util.ImageViewUtil.OnPushImageListener;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.ToastUtil;
import com.zbbt.sportslottery.util.UmengShare;

/**
 * @author kanle webview 中获取的图片手势放大缩小拖动
 */
public class ShowWebImageActivity extends SimpleBaseActivity {
	private ImageShowViewPager image_pager;
	private ImagePagerAdapter mAdapter;
	private TextView page_number;
	/** 图片列表 */
	private ArrayList<String> imgsUrl;
	private Bitmap[] imgbitmap;
	private int choicepic = 0;
	private UmengShare umengshare;
	private LinearLayout save_share_layout;
	private boolean isopen;
	private ImageView save_share;
	private GifImageView finder_img;
	private Boolean isfinder = false;
	private ProgressBarCircularIndetermininate progress;

	@Override
	protected void onActivityCreated(Bundle savedInstanceState) {
		setContentView(R.layout.activity_show_webimage);
		imgsUrl = getIntent().getStringArrayListExtra("img");
		choicepic = getIntent().getIntExtra("index", 0);
		if (imgsUrl.get(0).toString().substring(imgsUrl.get(0).toString().lastIndexOf(".") + 1).equals("gif")) {
			isfinder = true;
		}
		umengshare = new UmengShare(this);
	}

	@Override
	protected void initView() {
		page_number = (TextView) findViewById(R.id.page_number);
		image_pager = (ImageShowViewPager) findViewById(R.id.image_pager);
		finder_img = (GifImageView) findViewById(R.id.finder_img);
		save_share = (ImageView) findViewById(R.id.save_share);
		save_share_layout = (LinearLayout) findViewById(R.id.save_share_layout);
		LayoutInflater myInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout popView = (LinearLayout) myInflater.inflate(R.layout.item_save_share, null);
		TextView View1 = (TextView) popView.findViewById(R.id.img_save);
		View1.setOnClickListener(this);
		TextView View2 = (TextView) popView.findViewById(R.id.img_share);
		View2.setOnClickListener(this);
		save_share_layout.addView(popView);
		progress = (ProgressBarCircularIndetermininate) findViewById(R.id.progress);
		image_pager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				choicepic = arg0;
				if (imgsUrl != null && imgsUrl.size() != 0) {
					page_number.setText((arg0 + 1) + "/" + imgsUrl.size());
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
			}
		});
		initData();

	}

	public void SaveImage(Bitmap bitmap) {
		final String CAMERA_IMAGE_BUCKET_NAME = "/sdcard/dcim/camera";
		final String CAMERA_IMAGE_BUCKET_ID = String.valueOf(CAMERA_IMAGE_BUCKET_NAME.hashCode());
		ContentValues values = new ContentValues(8);
		String newname = "IMG_"
				+ DateFormat.format("yyyy-MM-dd kk.mm.ss", System.currentTimeMillis()).toString();
		values.put(MediaStore.Images.Media.TITLE, newname);// 名称，随便
		values.put(MediaStore.Images.Media.DISPLAY_NAME, newname);
		values.put(MediaStore.Images.Media.DESCRIPTION, "image");// 描述，随便
		values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());//
		// 图像的拍摄时间，显示时根据这个排序
		values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");//
		// 默认为jpg格式
		values.put(MediaStore.Images.Media.ORIENTATION, 0);//
		File parentFile = new File(CAMERA_IMAGE_BUCKET_NAME);
		String name = parentFile.getName().toLowerCase();
		values.put(Images.ImageColumns.BUCKET_ID, CAMERA_IMAGE_BUCKET_ID); // id

		values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
		// 先得到新的URI
		Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		try {
			// 写入数据
			OutputStream outStream = getContentResolver().openOutputStream(uri);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.close();
			// bitmap.recycle();
			ToastUtil.showLong("保存成功");
			return;
		} catch (Exception e) {
			LogUtil.printD(TAG, "exception while writing image");
		}
	}

	public static void saveImageToGallery(Context context, Bitmap bmp) {
		// if (sdcardExist) {
		// sdcardDir = Environment.getExternalStorageDirectory();
		// } else {
		// sdcardDir = Environment.getDataDirectory();
		// }
		// 首先保存图片
		File appDir = new File(Environment.getExternalStorageDirectory(), "fjtc");
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		String fileName = "IMG_" + System.currentTimeMillis() + ".jpg";
		File file = new File(appDir, fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 其次把文件插入到系统图库
		try {
			MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(),
					fileName, null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// 最后通知图库更新
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
		ToastUtil.showLong("已保存到相册/fjtc文件夹下");
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		save_share.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId())// 得到被点击的item的itemId
		{
		case R.id.save_share:
			if (isopen) {
				AnimationSet animSet = new AnimationSet(true);
				ScaleAnimation sa = new ScaleAnimation(1, (float) v.getWidth()
						/ ((View) v.getParent()).getWidth(), 1, (float) v.getHeight()
						/ ((View) v.getParent()).getHeight(), v.getX() / 2, 0);
				sa.setDuration(400);
				AlphaAnimation aa = new AlphaAnimation(1f, 0f);
				aa.setDuration(400);
				animSet.addAnimation(sa);
				animSet.addAnimation(aa);
				save_share_layout.setAnimation(animSet);
				save_share_layout.setVisibility(View.GONE);
				isopen = false;
			} else {
				AnimationSet animSet = new AnimationSet(true);
				ScaleAnimation sa = new ScaleAnimation((float) v.getWidth()
						/ ((View) v.getParent()).getWidth(), 1.0f, (float) v.getHeight()
						/ ((View) v.getParent()).getHeight(), 1.0f, v.getX() / 2, 0);
				sa.setDuration(400);
				AlphaAnimation aa = new AlphaAnimation(0.2f, 1);
				aa.setDuration(400);
				animSet.addAnimation(sa);
				animSet.addAnimation(aa);
				save_share_layout.startAnimation(animSet);
				save_share_layout.setVisibility(View.VISIBLE);
				isopen = true;
			}
			break;
		case R.id.img_save: // 对应的ID就是在add方法中所设定的Id
			if (choicepic >= 0) {
				if (imgbitmap[choicepic] != null) {
					// SaveImage(imgbitmap[choicepic]);
					saveImageToGallery(this, imgbitmap[choicepic]);
				} else {
					ToastUtil.showLong("载入图片中");
				}
				isopen = false;
				save_share_layout.setVisibility(View.GONE);
			}
			break;
		case R.id.img_share:
			if (choicepic >= 0) {
				if (imgbitmap[choicepic] != null) {
					umengshare.openshareimg(imgsUrl.get(choicepic), imgbitmap[choicepic]);
				} else {
					ToastUtil.showLong("载入图片中");
				}
				isopen = false;
				save_share_layout.setVisibility(View.GONE);
			}
			break;
		}
		super.onClick(v);
	}

	@Override
	protected void onClickEvent(View v) {
		// TODO Auto-generated method stub

	}

	protected void initData() {
		// TODO Auto-generated method stub
		if (imgsUrl != null && imgsUrl.size() != 0) {
			page_number.setText((choicepic + 1) + "/" + imgsUrl.size());
		}
		if (isfinder == true) {
			image_pager.setVisibility(View.GONE);
			finder_img.setVisibility(View.VISIBLE);
			imgbitmap = new Bitmap[1];
			choicepic = 0;
			AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
			asyncHttpClient.get(imgsUrl.get(choicepic), new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					progress.setVisibility(View.GONE);
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					GifDrawable drawable = null;
					try {
						drawable = new GifDrawable(arg2);
						imgbitmap[choicepic]=Bytes2Bimap(arg2);
					} catch (IOException e) {
						e.printStackTrace();
					}
					progress.setVisibility(View.GONE);
					drawable.start();
					finder_img.setImageDrawable(drawable);
				}

			});
		} else {
			progress.setVisibility(View.GONE);
			image_pager.setVisibility(View.VISIBLE);
			finder_img.setVisibility(View.GONE);
			initViewPager();
		}

	}
	private Bitmap Bytes2Bimap(byte[] b){
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// // TODO Auto-generated method stub
	// getMenuInflater().inflate(R.menu.share_save, menu);
	// return super.onCreateOptionsMenu(menu);
	// }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);
		return true;
	}

	private void initViewPager() {
		if (imgsUrl != null && imgsUrl.size() != 0) {
			imgbitmap = new Bitmap[imgsUrl.size()];
			mAdapter = new ImagePagerAdapter(getApplicationContext(), imgsUrl, imgbitmap);
			image_pager.setAdapter(mAdapter);
			image_pager.setCurrentItem(choicepic);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = UmengShare.mController.getConfig().getSsoHandler(requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}
}
